import { NextRequest, NextResponse } from 'next/server';
import UserModel from '@/models/user';

export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const jobId = params.id;
    
    if (!jobId || isNaN(Number(jobId))) {
      return NextResponse.json(
        { error: '无效的职位ID' },
        { status: 400 }
      );
    }
    
    // 查询职位详情
    const [jobs] = await UserModel.query<any[]>(
      `SELECT jp.*, c.name as company_name, c.logo as company_logo, c.industry as company_industry,
              c.location as company_location, c.size as company_size, c.description as company_description,
              c.website as company_website, u.username as creator_name
       FROM job_positions jp
       LEFT JOIN companies c ON jp.company_id = c.id
       LEFT JOIN users u ON jp.created_by = u.id
       WHERE jp.id = ? AND jp.status = 'active'`,
      [jobId]
    );
    
    if (!jobs || jobs.length === 0) {
      return NextResponse.json(
        { error: '职位不存在或已下线' },
        { status: 404 }
      );
    }
    
    // 增加浏览次数
    await UserModel.query(
      `UPDATE job_positions SET views = views + 1 WHERE id = ?`,
      [jobId]
    );
    
    // 返回结果
    return NextResponse.json({
      job: jobs[0]
    });
  } catch (error) {
    console.error('获取职位详情失败:', error);
    return NextResponse.json(
      { error: '获取职位详情失败' },
      { status: 500 }
    );
  }
}
